package router;

import model.HttpConfig;
import model.Router;

import java.util.List;
import java.util.Random;

/**
 * @author dsp
 * @date 2021-04-05
 */
public class MyHttpRouter implements NettyHttpRouter {

    private HttpConfig httpConfig;

    public MyHttpRouter(HttpConfig httpConfig) {
        this.httpConfig = httpConfig;
    }

    @Override
    public Router findRouter(String url) {
        String serverName = format(url);
        return httpConfig.getRoutersMap().get(serverName);
    }

    @Override
    public String route(Router router) {
        List<String> endpoints = httpConfig.getServerEndpoints().get(router.getServerName());
        // TODO 负载均衡
        int size = endpoints.size();
        Random random = new Random(System.currentTimeMillis());
        return endpoints.get(random.nextInt(size));
    }


}
